package eu.sweetlygeek.scrobbler.model;

import java.io.File;
import java.io.IOException;

import net.roarsoftware.lastfm.scrobble.Source;
import net.roarsoftware.lastfm.scrobble.SubmissionData;

import org.farng.mp3.AbstractMP3Tag;
import org.farng.mp3.TagException;
import org.joda.time.Duration;
import org.joda.time.Instant;
import org.joda.time.Seconds;

public class MP3File extends org.farng.mp3.MP3File {
	
	public MP3File(File file) throws IOException, TagException
	{
		super(file, false);
		this.seekMP3Frame();
	}
	
	public AbstractMP3Tag getTag()
	{
		if (hasID3v1Tag())
			 return getID3v1Tag();
		else if (hasID3v2Tag())
			return getID3v2Tag();
		else if (hasLyrics3Tag())
			return getLyrics3Tag();
		else if (hasFilenameTag())
			return getFilenameTag();
		else
			return null;
	}
	
	public SubmissionData toSubmissionData(Instant submittedOn) throws IOException
	{
		Duration duration = new Duration(submittedOn.getMillis());
		Seconds seconds = duration.toStandardSeconds();
		
		AbstractMP3Tag tag = getTag();
		String author = tag.getLeadArtist();
		String track = tag.getSongTitle();
		String album = tag.getAlbumTitle();
		int length = getLength();
		int number = 0;
		try {
			number = Integer.parseInt(tag.getTrackNumberOnAlbum());
		} catch (NumberFormatException e) {
			// Nothing
		}
		return new SubmissionData(author, track, album, length, number, Source.USER, seconds.getSeconds());
	}
	
	public int getLength() throws IOException
	{
		int bitrate = getBitRate() * 1024;
		long start = getMp3StartByte(); 
		long end = getMp3file().length();
		long length = (end - start) / (bitrate / 8);
		return Long.valueOf(length).intValue();
	}
}
